<template>
  <!------------------------- 规格弹窗 ------------------------->
  <!---------    说明
      此组件为规格展示与交互组件，用于快速下单商品多规格显示，商品详情页面规格显示
      props：
        data      ———— 商品信息
        pageType  ———— 页面类型(quickPlaceOrder,detail)
      method：
        closePopup  ———— 关闭弹窗
        addCart     ———— 加购物车
        buyNow      ———— 直接购买
   -->
  <div class="popup-content">
    <svg-icon icon-class="delete-2" class="color-gray fs-26 popup-close" @goPage="closePopup" />
    <div class="pb-170 pos-r" style="z-index:1;">
      <div class="flex pb-30 hb">
        <img-box class="is-200 br-10 flex-s-0" :img-url="changeData.ThumbnailUrl410" />
        <div class="prductItem-detail ml-20 flex-1">
          <!-- <p class="text-show-line-2 mb-10 fs-24">{{ changeData.ProductName }}</p> -->
          <p v-show="V_GradePrice" class="color-primary fs-40">
            <span class="fs-26">￥</span>{{ V_GradePrice
            }}<span v-show="changeData.BaseUnit" class="fs-26">/{{ changeData.BaseUnit }}</span>
          </p>
          <p class="color-gray fs-26">库存 {{ changeData.V_StockSum }}{{ changeData.DefaultUnit }}</p>
          <p v-show="changeData.MinNum && changeData.MinNum > 0" class="color-gray fs-26">起订 {{ changeData.MinNum }}</p>
          <p v-show="LimitBuy && LimitBuy > 0" class="color-gray fs-26">限购 {{ LimitBuy }}</p>
        </div>
      </div>
      <div v-if="changeData.DefaultUnit" class="skuItem hb">
        <p class="color-gray-light fs-24 mt-20">
          <span>单位</span>
          <span
            v-show="activeUnitName !== changeData.BaseUnit && changeData.BaseUnit"
          >(1{{ activeUnitName }}={{ activeUnitRatio }}{{ changeData.BaseUnit }})</span>
          <span>：</span>
        </p>
        <div v-if="changeData.UnitList && changeData.UnitList.length > 0" class="mt-20 flex-v-c flex-wrap">
          <div
            v-for="(item, index) in changeData.UnitList"
            :key="index"
            class="skuBtn"
            :class="activeUnitIndex === index ? 'color-primary' : ''"
            @click="changeUnit(index)"
          >
            {{ item }}
          </div>
        </div>
        <div v-else class="mt-20 flex-v-c flex-wrap">
          <div class="skuBtn color-primary">{{ changeData.DefaultUnit }}</div>
        </div>
      </div>
      <div class="skuItem">
        <!-- 多规格（第一规格） -->
        <div v-if="changeData.ProductAttributesList && changeData.ProductAttributesList.length > 0" class="skuItem hb">
          <p class="color-gray-light fs-24 mt-20">{{ ProductSkuAttrList[0].AttributeName }}：</p>
          <div class="mt-20 flex-v-c flex-wrap">
            <div
              v-for="(item, index) in ProductSkuAttrList"
              :key="index"
              class="skuBtn"
              :class="activeSpecIndex === index ? 'color-primary' : ''"
              @click="changeSpec(index)"
            >
              {{ item.ValueStr }}
            </div>
          </div>
        </div>
        <!-- 单规格 -->
        <div v-else>
          <div v-for="(item, index) in ProductSkuAttrList[0].SkuList" :key="index" class="flex-s-c mt-24 fs-28 ">
            <div class="flex-2 tal">
              <span>购买数量</span>
            </div>
            <div class="flex-1 tar flex-fe-c">
              <span
                class="btn-minus flex-s-0 "
                :class="item.Amount <= 0 ? 'color-shadow' : ''"
                @click="changeAmount(item, item.Amount, item.Stock, -1, changeData.MinNum, activeUnitRatio, item.LimitBuy)"
              >-</span>
              <div class="btn-input-box">
                <input
                  v-model="item.Amount"
                  type="number"
                  class="btn-input"
                  @blur="changeAmount(item, item.Amount, item.Stock, 0, changeData.MinNum, activeUnitRatio, item.LimitBuy)"
                >
              </div>
              <span
                class="btn-plus flex-s-0"
                :class="item.Amount >= item.Stock || (item.Amount >= item.LimitBuy && item.LimitBuy > 0) ? 'color-shadow' : ''"
                @click="changeAmount(item, item.Amount, item.Stock, 1, changeData.MinNum, activeUnitRatio, item.LimitBuy)"
              >+</span>
            </div>
          </div>
        </div>

        <!-- 第二规格 -->
        <div v-if="secondSpecList && secondSpecList.length > 0" class="skuItem">
          <div class="flex-s-c mt-24 color-gray-light fs-24 ">
            <div class="flex-1 tal">{{ secondSpecList[0].AttributeName || '规格' }}</div>
            <div class="flex-1 tac">库存</div>
            <div class="flex-1 tar">购买数量</div>
          </div>
          <div v-for="(item, index) in secondSpecList" :key="index" class="flex-s-c mt-24 fs-28 ">
            <div class="flex-1 tal">{{ item.AttributeNameSingle }}</div>
            <div class="flex-1 tac">{{ item.StockStr }}</div>
            <div class="flex-1 tar flex-fe-c">
              <span
                class="btn-minus flex-s-0 "
                :class="item.Amount <= 0 ? 'color-shadow' : ''"
                @click="changeAmount(item, item.Amount, item.Stock, -1, changeData.MinNum, activeUnitRatio, item.LimitBuy)"
              >-</span>
              <div class="btn-input-box">
                <input
                  v-model="item.Amount"
                  type="number"
                  class="btn-input"
                  @blur="changeAmount(item, item.Amount, item.Stock, 0, changeData.MinNum, activeUnitRatio, item.LimitBuy)"
                >
              </div>
              <span
                class="btn-plus flex-s-0"
                :class="item.Amount >= item.Stock || (item.Amount >= item.LimitBuy && item.LimitBuy > 0) ? 'color-shadow' : ''"
                @click="changeAmount(item, item.Amount, item.Stock, 1, changeData.MinNum, activeUnitRatio, item.LimitBuy)"
              >+</span>
            </div>
          </div>
        </div>
      </div>
      <div class="fixed-bottom  bottom-box">
        <button v-show="pageType === 'quickPlaceOrder'" class="btn-large color-white bg-primary" @click="addCart">加入购物车</button>
        <button v-show="pageType === 'detail'" class="btn-half color-white bg-second br-left" @click="addCart">加入购物车</button>
        <button v-show="pageType === 'detail'" class="btn-half color-white bg-primary br-right" @click="buyNow">立即购买</button>
      </div>
    </div>
  </div>
</template>

<script>
import imgBox from 'components/imgBox'
import { AddOrEditUserCarList } from 'api/product'
export default {
  name: 'ProductSpec',
  components: {
    imgBox
  },
  props: {
    data: {
      // 数据
      type: Object,
      required: true
    },
    fresh: {
      type: Boolean,
      required: false,
      default: false
    },
    storeId: {
      type: String,
      required: false,
      default: ''
    },
    pageType: {
      // 按钮类型
      type: String,
      required: false,
      default: 'quickPlaceOrder'
    },
		switch85:{
			type:Number,
			required: false,
			default:0
		}
  },
  data() {
    return {
      changeData: {},
      activeUnitIndex: -1,
      activeUnitName: '',
      activeUnitRatio: 1,
      activeSpecIndex: -1,
      secondSpecList: [],
      cartRequestObj: [],
      ProductSkuAttrList: [],
      V_GradePrice: '',
      LimitBuy: '',	
    }
  },
  watch: {
    data(newVal, oldVal) {
      console.log('商品变化')
      this.init()
    },
    fresh(newVal, oldVal) {
      console.log('gengxin')
      this.init()
    }
  },
  created() {
		
    this.init()		
  },
  methods: {
    init() {
			
      this.activeUnitIndex = -1
      this.activeUnitName = ''
      this.activeUnitRatio = 1
      this.activeSpecIndex = -1
      this.secondSpecList = []
      this.cartRequestList = []
      this.changeData = this.data
			console.log('changeData',this.changeData)
      this.ProductSkuAttrList = this.changeData.ProductSkuAttrList
      this.V_GradePrice = this.changeData.V_GradePrice
      this.LimitBuy = this.changeData.LimitBuy		
			if (this.changeData.UnitList && this.changeData.UnitList.length > 0) {
				this.changeData.UnitList.forEach((item, index) => {
					if (this.changeData.DefaultUnit === item) {
						this.activeUnitIndex = index
						this.activeUnitName = this.changeData.UnitList[index]
						this.activeUnitRatio = this.changeData.UnitratioList[index]
					}
				})
			} else {
				this.activeUnitName = this.changeData.BaseUnit
			}
			
			if (this.switch85 === 1) {
				this.deleteItem(this.changeData.DefaultUnit, this.changeData.UnitList);
				this.deleteItem(this.activeUnitRatio, this.changeData.UnitratioList);
				this.activeUnitName = this.changeData.UnitList[0]
     		this.activeUnitRatio = this.changeData.UnitratioList[0]		
			}

    },

		deleteItem (item, list) {
			// 先遍历list里面的每一个元素，对比item与每个元素是否相等，再利用splice的方法删除
			for (var key in list) {
				if (list[key] === item) {
					list.splice(key, 1)
				}
			}
		},
    // 关闭弹窗
    closePopup() {
      this.$emit('closePopup')
    },

    // 加入购物车
    addCart() {
      this.$emit('addCart', this.cartRequestList)
    },

    // 直接购买
    buyNow() {
      // this.$emit('buyNow', this.cartRequestList)
      const _obj = {}
      _obj.list = this.cartRequestList
      _obj.isTempCar = true
      _obj.isRemoveAll = true
      if (_obj.list && _obj.list.length > 0) {
        this.AddOrEditUserCarList(_obj)
      } else {
        this.$toast.fail('请添加商品')
      }
    },
    changeUnit(index) {
      this.activeUnitIndex = index
      this.activeUnitName = this.changeData.UnitList[index]
      this.activeUnitRatio = this.changeData.UnitratioList[index]
    },
    changeSpec(index) {
      this.activeSpecIndex = index
      this.secondSpecList = this.changeData.ProductSkuAttrList[index].SkuList
      if (this.secondSpecList && this.secondSpecList.length > 0) {
        this.secondSpecList.forEach(item => {
          item.AttributeNameSingle = item.AttributeNameSingle || item.AttributeNameValue
        })
      }
    },
    changeAmount(item, num, stock, type, minNum, UnitRatio, LimitBuy) {
      if(item.IsLock==1){
        this.$toast('该商品已禁用')
        return
      }
      this.$utils.changeAmount(item, num, stock, type, minNum, UnitRatio, LimitBuy)
      const _obj = {}
      _obj.ProductId = item.ProductId
      _obj.Amount = item.Amount
      _obj.SkuId = item.ID
      if(this.storeId){
          _obj.StoreId = this.storeId
        }
      _obj.Source = 1
      let _newObj = true
      this.V_GradePrice = item.V_GradePrice
      this.LimitBuy = item.LimitBuy
      if (this.cartRequestList && this.cartRequestList.length > 0) {
        for (let i = 0; i < this.cartRequestList.length; i++) {
          if (_obj.SkuId === this.cartRequestList[i].SkuId && _obj.ProductId === this.cartRequestList[i].ProductId) {
            this.cartRequestList[i].Amount = _obj.Amount
            _newObj = false
            break
          }
        }
      }
      if (_newObj) {
        this.cartRequestList.push(_obj)
      }
    },

    AddOrEditUserCarList(obj) {
      AddOrEditUserCarList(obj).then(res => {
        if (res) {
          window.location.href = this.$LocalDomain + '/m/product/ProductSubmitOrder?InfoType=1'
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
// 弹窗组件
.popup-content {
  padding: 30px;
  position: relative;
  background: $colorF;
  border-radius: 40px 40px 0 0;
  .popup-close {
    position: absolute;
    right: 30px;
    top: 30px;
    z-index: 5;
  }
  .prductItem-detail {
    position: relative;
    .prductItem-p-left {
      position: absolute;
      bottom: 0;
      left: 0;
    }
    .prductItem-p-right {
      position: absolute;
      bottom: 0;
      right: 0;
    }
  }
  .skuItem {
    padding-bottom: 4px;
    .skuBtn {
      position: relative;
      font-size: 28px;
      line-height: 64px;
      padding: 0 30px;
      min-width: 136px;
      border-radius: 8px;
      overflow: hidden;
      margin: 0 20px 20px 0;
      text-align: center;
      &:before {
        content: '';
        position: absolute;
        height: 100%;
        width: 100%;
        background: currentColor;
        opacity: 0.1;
        top: 0;
        left: 0;
      }
    }
    .btn-input-box {
      position: relative;
      margin: 0 4px;
      &:before {
        content: '';
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        background: currentColor;
        opacity: 0.1;
      }
      .btn-input {
        position: relative;
        z-index: 1;
        height: 56px;
        width: 80px;
        line-height: 1;
        border: none;
        // background: transparent;
        text-align: center;
      }
    }
    .btn-minus,
    .btn-plus {
      position: relative;
      font-size: 45px;
      line-height: 56px;
      height: 56px;
      width: 56px;
      text-align: center;
      overflow: hidden;
      border-radius: 0 8px 8px 0;
      &:before {
        content: '';
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        background: currentColor;
        opacity: 0.1;
      }
    }
    .btn-minus {
      border-radius: 8px 0 0 8px;
    }
  }
}
.bottom-box {
  padding: 0 30px 50px 30px;
  display: flex;
  align-items: center;
  .br-left {
    border-radius: 44px 0 0 44px;
  }
  .br-right {
    border-radius: 0 44px 44px 0;
  }
}
</style>
